package com.bw.mvvm.network.inteceptor;

import com.bumptech.glide.RequestBuilder;
import com.bw.mvvm.utils.SignUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * sign 获取request
 * 新建request
 * 将原来的url以及header赋值到新的request
 * 获取原有的 body
 * 获取body的字符串  解析json字符串
 * 获取解析的json串 然后生成sign
 * 创建新的body  添加到新request返回回去
 */
public class SignInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = new Request.Builder();
        builder.url(request.url());
        builder.headers(request.headers());
        RequestBody body = request.body();
        if (body == null){
            return chain.proceed(request);
        }
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        byte[] bytes = new byte[1024];
        String json = "";
        while (buffer.read(bytes) != -1){
            json+= new String(bytes);
        }
        buffer.flush();
        buffer.close();
        String value = "";
        String result = "";
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()){
                value += jsonObject.getString(keys.next());
            }
            String sign = SignUtils.createSign(value);
            jsonObject.put("sign",sign);
            result = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body1 = RequestBody.create(MediaType.parse("application/json"),result);
        builder.post(body1);
        return chain.proceed(builder.build());
    }
}
